﻿using Fall.Core.BaseModels;
using Fall.Core.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Fall.Core.Http
{
    /// <summary>
    /// Http返回结果序列化
    /// </summary>
    public static class HttpResponseMessageExtensions
    {
        public static async Task<TResult> Serialize<TResult>(this HttpResponseMessage httpResponse)
        {
            var str = await httpResponse.Content.ReadAsStringAsync();
            return JsonSerializer.Deserialize<TResult>(str);
        }

        public static async Task<TResult> FallSerialize<TResult>(this HttpResponseMessage httpResponse)
        {
            var str = await httpResponse.Content.ReadAsStringAsync();
            var commonResult = JsonSerializer.Deserialize<CommonResult<TResult>>(str);
            if (!commonResult.IsSuccess) throw new UserFriendlyException($"{commonResult.ErrorResult.Detail}");
            return commonResult.Result;
        }
    }
}
